package com.gongpingjialoan.activity.car;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.adapter.PriceChangeAdapter;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.CarSource;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.widget.LoadingDialog;
import com.handmark.pulltorefresh.library.PullToRefreshAndSwipeMenuListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.swipemenu.library.SwipeMenu;
import com.handmark.pulltorefresh.library.swipemenu.library.SwipeMenuCreator;
import com.handmark.pulltorefresh.library.swipemenu.library.SwipeMenuItem;
import com.handmark.pulltorefresh.library.swipemenu.library.SwipeMenuListView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/2/29.
 */
public class RemindPriceChangeActivity extends BaseActivity implements NetDataJson.OnNetDataJsonListener, PullToRefreshBase.OnLastItemVisibleListener, PullToRefreshBase.OnRefreshListener<SwipeMenuListView>, View.OnClickListener {

    private TextView deleteAllTextView;
    private PullToRefreshAndSwipeMenuListView mPullToRefreshAndSwipeMenuListView;
    private SwipeMenuListView mSwipeMenuListView;
    private View footview;
    private NetDataJson netWork;

    private NetDataJson canclenetWork;
    private PriceChangeAdapter mPriceChangeAdapter;
    private List<CarSource> carSourceDataList;
    private int pageIndex = 1;

    private boolean isRefresh = true;

    private boolean isLoadingMore;

    private boolean hasMore;

    private ImageView nocarImageView;

    private LoadingDialog mLoadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.remind_price_layout);
        EventBus.getDefault().register(this);
        setTitle("调价提醒");
        netWork = new NetDataJson(this);
        mLoadingDialog = new LoadingDialog(this);
        footview = LayoutInflater.from(this).inflate(R.layout.listview_footview, null);
        deleteAllTextView = (TextView) (this).findViewById(R.id.right_title);
        deleteAllTextView.setText("清空");
        deleteAllTextView.setOnClickListener(this);
        deleteAllTextView.setVisibility(View.VISIBLE);
        nocarImageView = (ImageView) findViewById(R.id.no_car_id);
        mPullToRefreshAndSwipeMenuListView = (PullToRefreshAndSwipeMenuListView) findViewById(R.id.listview);
        mPullToRefreshAndSwipeMenuListView.setScrollingWhileRefreshingEnabled(false);
        mPullToRefreshAndSwipeMenuListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        mPullToRefreshAndSwipeMenuListView.setOnRefreshListener(this);
        mPullToRefreshAndSwipeMenuListView.setOnLastItemVisibleListener(this);
        mSwipeMenuListView = mPullToRefreshAndSwipeMenuListView.getRefreshableView();
        mSwipeMenuListView.addFooterView(footview);
        carSourceDataList = new ArrayList<>();
        mPriceChangeAdapter = new PriceChangeAdapter(this);
        mSwipeMenuListView.setAdapter(mPriceChangeAdapter);
        mSwipeMenuListView.removeFooterView(footview);
        mPriceChangeAdapter.notifyDataSetChanged();
        initSwipeMenu();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mPullToRefreshAndSwipeMenuListView.setRefreshing();
            }
        }, 500);

        canclenetWork = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
                mLoadingDialog.hide();
                Toast.makeText(RemindPriceChangeActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDataJsonUpdate(JSONObject json) {
                mLoadingDialog.hide();
                Toast.makeText(RemindPriceChangeActivity.this, "取消成功", Toast.LENGTH_SHORT).show();
                mPullToRefreshAndSwipeMenuListView.setRefreshing();
            }
        });
        canclenetWork.setUrl(API.delete_price_change_remind);

        mSwipeMenuListView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public void onMenuItemClick(int position, SwipeMenu menu, int index) {
                mLoadingDialog.show();
                canclenetWork.clearMap();
                canclenetWork.addParam("car_ids", carSourceDataList.get(position).mId);
                canclenetWork.request("post");
            }
        });
        mSwipeMenuListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                intent.setClass(RemindPriceChangeActivity.this, CarBuyDetailActivity.class);
                intent.putExtra("typevalue", carSourceDataList.get(position).mId + "");
                intent.putExtra("type", "remindprice");
                intent.putExtra("from", "pricechange");
                startActivity(intent);
            }
        });


    }

    private void initData() {
        netWork.setUrl(API.remindcars_Search);
        netWork.addParam("page", pageIndex);
        netWork.request("get");
    }


    private void refreshData() {
        isRefresh = true;
        nocarImageView.setVisibility(View.GONE);
        pageIndex = 1;
        hasMore = true;
        initData();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refresh(Object o) {
        if ("remind".equals(o.toString()))
            mPullToRefreshAndSwipeMenuListView.setRefreshing();
    }


    private void initSwipeMenu() {
        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                int width = getWindowManager().getDefaultDisplay().getWidth();
                SwipeMenuItem item1 = new SwipeMenuItem(RemindPriceChangeActivity.this);
                item1.setBackground(R.drawable.cancle_bg);
                item1.setTitle("取消提醒");
                item1.setTitleColor(getResources().getColor(R.color.text_grey_dark));
                item1.setTitleSize(15);
                item1.setWidth((int) (width / 4.6));
                menu.addMenuItem(item1);
            }
        };
        mSwipeMenuListView.setMenuCreator(creator);
    }


    @Override
    public void onRefresh(PullToRefreshBase<SwipeMenuListView> refreshView) {
        refreshData();
    }

    @Override
    public void onLastItemVisible() {
        LoadMoreData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (netWork != null) {
            netWork.cancelTask();
        }
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onDataJsonError(String errorMessage) {
        Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
        if (isLoadingMore && !isRefresh) {
            mSwipeMenuListView.removeFooterView(footview);
        }
        isLoadingMore = false;
        mPullToRefreshAndSwipeMenuListView.onRefreshComplete();
    }

    @Override
    public void onDataJsonUpdate(JSONObject json) {
        JSONArray jsonArray = null;
        if (isLoadingMore && !isRefresh) {
            mSwipeMenuListView.removeFooterView(footview);
        }
        if (isRefresh) {
            carSourceDataList.clear();
            mPriceChangeAdapter.notifyDataSetChanged();
        }
        try {
            jsonArray = json.getJSONArray("remind_list");
            // Log.e("jsonArray", jsonArray.toString());
            if (0 == jsonArray.length()) {
                nocarImageView.setVisibility(View.VISIBLE);
                isLoadingMore = false;
                mPullToRefreshAndSwipeMenuListView.onRefreshComplete();
                return;
            }

            getDataFromJsonArray(jsonArray);

            int page_num = json.getInt("total_page");
            if (page_num == pageIndex) {
                hasMore = false;
            }

        } catch (JSONException e) {
            isLoadingMore = false;
            Toast.makeText(this, "未找到相应数据", Toast.LENGTH_SHORT).show();
            mPullToRefreshAndSwipeMenuListView.onRefreshComplete();
            return;
        }
        updateListView();
    }


    public void updateListView() {
        if (carSourceDataList.size() != 0) {
            // mPriceChangeAdapter.setData(carSourceDataList);
            mPullToRefreshAndSwipeMenuListView.onRefreshComplete();
            nocarImageView.setVisibility(View.GONE);
            isLoadingMore = false;
        } else {
            nocarImageView.setVisibility(View.VISIBLE);
        }
    }


    private void getDataFromJsonArray(JSONArray jsonArray) throws JSONException {
        // Log.e("getDataFromJsonArray", "getDataFromJsonArray");
        for (int i = 0; i < jsonArray.length(); i++) {
            CarSource carSrc = new CarSource();
            JSONObject object = jsonArray.getJSONObject(i);
            carSrc.mCity = "";
            carSrc.mTitle = object.getString("title");
            carSrc.mYear = object.getString("year");
            carSrc.mMile = object.getString("mile").equals("None") ? "" : object.getString("mile");
            carSrc.mPrice = Double.valueOf(object.getString("price"));
            carSrc.mId = object.getInt("car_id");
            carSrc.mThumbnail = object.getString("thumbnail");
            //carSrc.mTime = object.getString("time");
            carSrc.hasmodel = object.getString("has_model_detail");
            carSrc.is_certify = object.getBoolean("is_certify");
            // carSrc.mRecommend = object.getString("recommend");
            carSrc.mSourceType = object.getString("source_type");
            carSrc.mGpjIndex = object.getDouble("gpj_index");
            carSrc.mQsTags = object.getString("qs_tags");
            carSrc.mSource = object.getString("domain");
            carSrc.dealer_category = object.getString("dealer_category");
            carSrc.pubTime = object.getString("pub_time");
            carSrc.brand_zh = object.getString("brand_slug_zh");
            carSrc.model_zh = object.getString("model_slug_zh");
            carSrc.model_detail_zh = object.getString("model_detail_slug_zh");

            carSrc.setBrand(object.getString("brand_slug"));
            carSrc.setModel(object.getString("model_slug"));

            carSrc.mUrl = carSrc.mThumbnail;
            carSourceDataList.add(carSrc);
        }
    }


    // 加载更多
    private void LoadMoreData() {
        if (!hasMore) {
            Toast.makeText(this, "没有更多了", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!isLoadingMore && hasMore && carSourceDataList.size() > 0) {
            mSwipeMenuListView.addFooterView(footview);
            mSwipeMenuListView.setSelection(mSwipeMenuListView.getBottom());
            isRefresh = false;
            isLoadingMore = true;
            pageIndex++;
            initData();
        }
    }

    @Override
    public void onClick(View v) {
        if (v == deleteAllTextView) {
            AlertDialog.Builder ad = new AlertDialog.Builder(this);
            ad.setTitle("提示");
            ad.setMessage("确定清空所有提醒？");
            ad.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mLoadingDialog.show();
                    canclenetWork.clearMap();
                    canclenetWork.addParam("car_ids", "all");
                    canclenetWork.request("post");
                }
            });
            ad.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            ad.create().show();
        }
    }
}
